/*
 *  jose_main.c
 *
 *  (C) 2011 Harry Wei
 */
 
/*  
 * This program is just for the famous problem, 
 * josephus. I use the linear list to achieve it.
 * Note: It is linked-linear-list.
 */

#include <stdio.h>
#include <stdlib.h>
#include "jose.h"

int main(int argc, char *argv[], char **env)
{
	int a; /*all the people*/
	int i = 1; /*Recycle parameter*/
	int j = 0; /*The first password for Josephus*/
	struct jose *b = NULL; /*All the pointers for us*/
	struct jose *c = NULL;
	struct jose *d = NULL;

//	srand(time(NULL));
	do {
//		a = rand() % 101;
		a = 7;
	} while (!a);
	printf("There are %d people\n", a);
	do {
//		j = rand() % 101;
		j = 20;
	} while (!j);
	printf("The first password is %d\n", j);
	d = c = b = (struct jose *)malloc(sizeof(struct jose));
	if (!b) {
		printf("Allocate error!\n");
		return 1;
	}
	/*Establish the list*/
	while (i <= a) {
		d = (struct jose*)malloc(sizeof(struct jose));
		if (!d) {
			printf("Allocaate error!\n");
			return 1;
		}
		d->number = i;
		printf("This is %d\n", d->number);
		do {
	//		d->passwd = rand() % 101;
			printf("Enter %d's passwd:", d->number);
			scanf("%d", &d->passwd);
		} while (!d->passwd);
		printf("Its passwd is %d\n", d->passwd);
		c->next = d;
		c = d;
		i++;
	}
	c->next = NULL;
	c = b->next;
	while (!c) {
		printf("%d  %d\n", c->number, c->passwd);
		c = c->next;
	}
	i = 0;
	d -> next = b->next; /*Finish the sigle-linked-linear-list*/
	free(b);
	b = c = d;
	d = d->next;
	/*Get all the out numbers*/
	while (i <= a) {
//		c = c->next;
//		d = d->next;
//		j = j - 1;
		if ( 1 == j ) {
			printf("%-6d", d->number);
			j = d->passwd;
			b = d;
			d = d->next;
			c->next = d;
			free(b);
			i = i + 1;
		}
		j = j - 1;
		c = c->next;
		d = d->next;
	}
	putchar('\n');
	return 0;
}
